package edu.ua.bmr.android;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

/**
 * Quick activity which displays class data passed from the Intent.
 * 
 * Please note the required fields in "EXTRAS". Also, this class expects
 * an intent that has a string extra called "registered". This "registered"
 * field can be 0 for false or elsewise for true if the user has registered for
 * the class being displayed. It affects the add/drop logic of this activity.
 * @author OEP
 *
 */
public class ClassActivity extends Activity implements Runnable {
	private static final String TAG = "ClassActivity";
	
	private String mCRN;
	private Dialog mWaitDialog;
	private Dialog mConfirmDialog;
	private Button mAddDropButton;
	private Intent mIntent = new Intent();
	
	public static final int RESULT_CLEAN = 0;
	public static final int RESULT_DIRTY = 1;
	
	private View.OnClickListener mButtonClicked = new View.OnClickListener() {
		public void onClick(View v) {
			if(mStudentHasClass) {
				// User is dropping the class. Ask them to confirm.
				mConfirmDialog.show();
			}
			else {
				doAddDropAction();
			}
		}
	};
	
	private DialogInterface.OnClickListener mConfirmDialogClicked = new DialogInterface.OnClickListener() {

		public void onClick(DialogInterface dialog, int which) {
			switch(which) {
			case DialogInterface.BUTTON_POSITIVE:
				doAddDropAction();
				break;
			}
			dialog.dismiss();
		}
		
	};

	private boolean mStudentHasClass;
	
	public static final String[] EXTRAS =
		{ "dept", "code", "section", "title", "instructor", "days", "times",
			"capacity", "actual", "wcapacity", "wactual", "location" };
	
	public static final int[] FIELDS = 
	{ R.id.class_department, R.id.class_number, R.id.class_section, R.id.class_title,
		R.id.class_instructor, R.id.class_days, R.id.class_time, R.id.class_cap,
		R.id.class_actual, R.id.class_waitlist_cap, R.id.class_waitlist_actual, R.id.class_location };
	
	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		this.setContentView(R.layout.act_class);		
		this.setTitle( R.string.class_details );
		
		// Prepare to echo back the data passed to us
		Bundle b = getIntent().getExtras();
		mIntent.putExtras(b);
		setResult(RESULT_CLEAN, mIntent);
		
		updateTextViews();
		updateState();
		setupUI();
	}
	
	protected void doAddDropAction() {
		// User is adding the class. This is no problem. Just do it.
		mWaitDialog = BMR.showProgressDialog(ClassActivity.this,
				R.string.please_wait,
				R.string.communicating_with_server);
		
		Thread t = new Thread(ClassActivity.this);
		t.start();
	}

	/**
	 * To be called AFTER updateState()
	 */
	private void setupUI() {
		mAddDropButton = (Button) this.findViewById(R.id.class_add_drop_button);
		
		mAddDropButton.setOnClickListener(mButtonClicked);
		
		Session s = Session.getInstance();

		// Set the proper label and enabled state
		if(mStudentHasClass) {
			mAddDropButton.setText(R.string.drop_this_class);
			mAddDropButton.setEnabled( s.isDroppable() );
		}
		else {
			mAddDropButton.setText(R.string.add_this_class);
			mAddDropButton.setEnabled( s.isAddable() );
		}
		
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		
		mConfirmDialog = builder.setCancelable(true)
			.setTitle(R.string.confirm_drop_title)
			.setMessage(R.string.confirm_drop_message)
			.setIcon(android.R.drawable.ic_dialog_alert)
			.setPositiveButton(R.string.yes, mConfirmDialogClicked)
			.setNegativeButton(R.string.no, mConfirmDialogClicked)
			.create();
		
		
	}

	/**
	 * Pick out data from the intent and update a few
	 * state-changing variables.
	 */
	private void updateState() {
		Intent intent = getIntent();
		mCRN = intent.getStringExtra(BMR.TABLE_CLASSES_CRN);
		String flag = intent.getStringExtra(BMR.KEYWORD_REGISTERED);
		
		// Student has the class when the flag is not equal to 0.
		// The following line of code hurts to think about so perhaps
		// that it should be noted that I am following C conventions for
		// representing booleans as integer data types.
		//    TRUE --> != FALSE
		//    FALSE --> = 0
		mStudentHasClass = flag.compareTo("0") != 0;
	}

	/**
	 * Iterate through the intent and assign the TextViews in our layout
	 * the data which was passed to us.
	 */
	private void updateTextViews() {
		if(EXTRAS.length != FIELDS.length) {
			Log.e(TAG, "Extra names != Fields length");
			return;
		}
		
		Intent intent = this.getIntent();
		for(int i = 0; i < EXTRAS.length; i++) {
			TextView t = (TextView) this.findViewById(FIELDS[i]);
			t.setText( intent.getStringExtra(EXTRAS[i]) );
		}
	}
	
	private Handler mAddDropHandler = new Handler() {
		public void handleMessage(Message msg) {
			mWaitDialog.dismiss();
			if(msg.arg1 != 0) {
				Bundle b = msg.getData();
				boolean success = b.getBoolean(BMR.KEYWORD_RESULT);
				
				if(success) {
					int rid = (mStudentHasClass) ? R.string.successful_drop : R.string.successful_add;
					Toast.makeText(ClassActivity.this, rid, Toast.LENGTH_LONG).show();
					
					// The student's havingness of the class has negated
					mStudentHasClass = !mStudentHasClass;
					
					// Update the intent we send back to the receiver.
					if(mStudentHasClass) {
						mIntent.putExtra(BMR.KEYWORD_REGISTERED, "1");
					}
					else {
						mIntent.putExtra(BMR.KEYWORD_REGISTERED, "0");
					}
					
					setResult(RESULT_DIRTY, mIntent);
					
					// Class list data is dirty... recache it.
					Session.getInstance().forceClasslistRecache();
					
					// Update our widgets!!
					setupUI();
				}
				else {
					String reply = b.getString(BMR.KEYWORD_MSG);
					Toast.makeText(ClassActivity.this, reply, Toast.LENGTH_LONG).show();
				}
			}
			else {
				Toast.makeText(ClassActivity.this, msg.arg2, Toast.LENGTH_LONG).show();
			}
		}
	};

	public void run() {
		Session s = Session.getInstance();
		
		Message msg = new Message();
		try {
			ArrayList<HashMap<String,String>> result;
			
			// If the student has the class, we should drop.
			// If the student doesn't have the class, we should add.
			if(mStudentHasClass) {
				// Student has the class. Drop it. Drop it, boy! Go get the stick!
				result = s.dropClass(mCRN);
			}
			else {
				// Student doesn't have the class. Try to add it.
				result = s.addClass(mCRN);
			}
			
			// No exceptions. Check the data we were passed.
			msg.arg1 = 1;
			
			/*
			 * A note from Paul:
			 * While I actually coded the backend to take a comma-delimited
			 * list of CRNs and should be able to handle lots of class 
			 * registrations. However, we don't have anything in software
			 * that facilitates adding multiple classes at once. So, at this
			 * point it should be noted that I am treating all cases
			 * as if we only tried to register for one class.
			 */
			HashMap<String,String> single = result.get(0);
			Bundle b = new Bundle();
			b.putBoolean(BMR.KEYWORD_RESULT, single.get(BMR.KEYWORD_RESULT).compareTo("0") != 0);
			b.putString(BMR.TABLE_CLASSES_CRN, single.get(BMR.TABLE_CLASSES_CRN));
			b.putString(BMR.KEYWORD_MSG, single.get(BMR.KEYWORD_MSG));
			msg.setData(b);
		}
		catch(BMRException e) {
			// Action ended in exception.
			msg.arg1 = 0;
			msg.arg2 = e.getResourceId();
		}
		
		mAddDropHandler.sendMessage(msg);
	}
}
